import UIKit
import Lottie

protocol ControllerNavHidden {
    func navIsNeed() -> Bool
}

// 定义一个刷新数据的协议
protocol Refreshable {
    func refreshData()
}

class CommonLoadingView: UIView {
    
    private let loadingSize: CGSize = {
        return CGSize(width: 70, height: 70)
    }()
    
    var isLoading: Bool {
        return loadingView.isAnimationPlaying
    }
    
    let loadingView: LottieAnimationView = {
        let loadingView = LottieAnimationView(name: "loading")
        loadingView.loopMode = .loop
        return loadingView
    }()
    let showTextLab: UILabel = {
        let showTextLabel = UILabel()
        showTextLabel.font = kSetPingFangRegular(17)
        showTextLabel.textAlignment = .center
        showTextLabel.textColor = UIColor.hex(hexString: "FFFFFF")
        showTextLabel.isHidden = true
        return showTextLabel
    }()
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor.hex(hexString: "F4F4F5 ",a: 0.6)
        didinitialized()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        
        didinitialized()
    }
    
    func didinitialized() {
        isHidden = true
        self.addSubview(self.loadingView)
        self.addSubview(self.showTextLab)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        self.loadingView.frame = CGRect(x: (screenWidth - loadingSize.width)/2, y: (frame.size.height - loadingSize.height)/2, width: loadingSize.width, height: loadingSize.height)
        self.showTextLab.frame = CGRect(x: 0, y: self.loadingView.frame.origin.y + loadingSize.height + 15, width: screenWidth, height: 19)
    }
    
    func loading() {
        self.isHidden = false
        self.loadingView.play()
    }
    func loadingWithText(showText : String) {
        
        self.loadingView.play()
        self.isHidden = false
        self.showTextLab.text = showText
        self.showTextLab.isHidden = false
        
    }
    func stopLoading() {
        self.isHidden = true
        self.showTextLab.isHidden = true
        self.loadingView.stop()
    }
}

class BaseViewController: UIViewController, Refreshable {

    var navIsHidden: Bool? = true
    let loadingView = CommonLoadingView()
    
    init() {
        super.init(nibName: nil, bundle: nil)
        self.modalPresentationStyle = .fullScreen
        
        if #available(iOS 11.0, *) {
            UIScrollView.appearance().contentInsetAdjustmentBehavior = .never
        }else {
            automaticallyAdjustsScrollViewInsets = false
        }
    }
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        didinitialized()
    }
    
    required public init?(coder: NSCoder) {
        super.init(coder: coder)
        didinitialized()
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if #available(iOS 15.0, *) {
            UITableView.appearance().sectionHeaderTopPadding = 0
        }
        initSubviews()
        bindViewModel()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        configNavigationBar()
        if !loadingView.isHidden && !loadingView.isLoading {
            startloading()
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        view.endEditing(true)
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        loadingView.frame = self.view.bounds
    }
    
    func didinitialized() {
        
    }
    
    func refreshData() {
        
    }
    
    func initSubviews() {
        view.backgroundColor = UIColor.white
        view.addSubview(self.loadingView)
    }
    
    func bindViewModel() {
        
    }
    
    func configNavigationBar() {
        guard let nav = navigationController else {return}
        if nav.getVisibleViewController == self {
            navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "back_pop_black")?.withRenderingMode(.alwaysOriginal), style: .done, target: self, action: #selector(backAction)) // self.presentingViewController == nil ? "back_pop_black":"close_black"
        }
    }
    
    @objc func backAction() {
        
        view.endEditing(true)
        
        guard (self.presentingViewController == nil) else {
            
            self.dismiss(animated: true) {}
            return
        }
        navigationController?.popViewController(animated: true)
    }
    
    open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true);
    }
    
}

extension BaseViewController {
    
    func startloading() {
        self.view.bringSubviewToFront(self.loadingView)
        self.loadingView.loading()
    }
    func startloadingWithText(_ text:String) {
        self.view.bringSubviewToFront(self.loadingView)
        self.loadingView.loadingWithText(showText: text)
    }
    func stoploading() {
        self.loadingView.stopLoading()
    }
}

extension BaseViewController {
    
    open override var preferredStatusBarStyle: UIStatusBarStyle{
        return .default
    }
    
}

extension BaseViewController {
    
    open override func present(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)? = nil) {
        if #available(iOS 13, *) {
            viewControllerToPresent.modalPresentationStyle = .fullScreen
        }
        super.present(viewControllerToPresent, animated: flag, completion: completion)
    }
}

extension BaseViewController: ControllerNavHidden {
    func navIsNeed() -> Bool {
        return navIsHidden ?? false
    }
}

// MARK: - 屏幕旋转
extension BaseViewController {
    
    ///强制横屏
    func forceOrientationLandscape() {
        let appdelegate = UIApplication.shared.delegate as! AppDelegate
        appdelegate.isForceLandscape = true
        appdelegate.isForcePortrait = false
        _ = appdelegate.application(UIApplication.shared, supportedInterfaceOrientationsFor: self.view.window)
        
        //强制翻转屏幕，Home键在右边。
        UIDevice.current.setValue(UIInterfaceOrientation.landscapeRight.rawValue, forKey: "orientation")
        //刷新
        UIViewController.attemptRotationToDeviceOrientation()
        
    }
    
    ///强制竖屏
    func forceOrientationPortrait() {
        let appdelegate = UIApplication.shared.delegate as! AppDelegate
        appdelegate.isForceLandscape = false
        appdelegate.isForcePortrait = true
        _ = appdelegate.application(UIApplication.shared, supportedInterfaceOrientationsFor: self.view.window)
        
        //强制翻转屏幕，Home键在右边。
        UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
        //刷新
        UIViewController.attemptRotationToDeviceOrientation()
        
    }
    
    /// 自动
    func allOrientationPortrait() {
        let appdelegate = UIApplication.shared.delegate as! AppDelegate
        appdelegate.isForceLandscape = false
        appdelegate.isForcePortrait = false
        _ = appdelegate.application(UIApplication.shared, supportedInterfaceOrientationsFor: self.view.window)
        
        //强制翻转屏幕，Home键在右边。
        UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
        //刷新
        UIViewController.attemptRotationToDeviceOrientation()
        
    }
    
    override var shouldAutorotate: Bool {
        return true
    }
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    
    override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
        return .portrait
    }
    
    
}
